import threading
import pyttsx3
import pygame

class SpeechManager:
    def __init__(self):
        self.engine = None
        pygame.mixer.init()
        self.init_engine()
        
    def init_engine(self):
        """初始化语音引擎"""
        try:
            self.engine = pyttsx3.init()
            # 设置语音属性
            self.engine.setProperty('rate', 150)    # 语速
            self.engine.setProperty('volume', 1.0)  # 音量
            
            # 尝试设置中文声音
            voices = self.engine.getProperty('voices')
            for voice in voices:
                if 'chinese' in voice.name.lower() or 'chinese' in voice.languages[0].lower():
                    self.engine.setProperty('voice', voice.id)
                    break
            
            print("语音引擎初始化成功")
        except Exception as e:
            print(f"语音引擎初始化失败: {str(e)}")
            self.engine = None
            
    def speak(self, text, async_mode=True):
        """播放文本
        
        Args:
            text: 要播放的文本
            async_mode: 是否异步播放（不阻塞主线程）
        """
        if not self.engine:
            print("语音引擎未初始化")
            return
            
        try:
            if async_mode:
                # 在新线程中播放，避免阻塞主线程
                thread = threading.Thread(target=self._speak_thread, args=(text,))
                thread.daemon = True  # 设置为守护线程，随主线程退出
                thread.start()
            else:
                self._speak_thread(text)
        except Exception as e:
            print(f"语音播放失败: {str(e)}")
            
    def _speak_thread(self, text):
        """在新线程中播放语音"""
        try:
            self.engine.say(text)
            self.engine.runAndWait()
        except Exception as e:
            print(f"语音播放线程出错: {str(e)}")
            
    def stop(self):
        """停止当前播放"""
        try:
            self.engine.stop()
        except:
            pass
                
    def cleanup(self):
        """清理资源"""
        try:
            self.engine.stop()
        except:
            pass
        self.engine = None 